package lew.bing.tom;

import groovy.lang.Script;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ThymeleafHtmlHandler implements HtmlHandler{

    private TemplateEngineProvider templateEngineProvider;

    public ThymeleafHtmlHandler(TemplateEngineProvider templateEngineProvider) {
        this.templateEngineProvider = templateEngineProvider;
    }

    @Override
    public void handler(HttpServletRequest request, HttpServletResponse response) {


        final TemplateEngine engine = templateEngineProvider.engine();
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        final String uri = request.getRequestURI();
        final WebContext webContext = new WebContext(request, response, request.getServletContext());
        webContext.setVariable("test","123");
        webContext.setVariable("aObject", new TestObject());

        handlerScript(request, webContext);

        try {
            engine.process(uri, webContext, response.getWriter());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handlerScript(HttpServletRequest request, WebContext webContext) {
        final String requestURI = request.getRequestURI();
        final int i = requestURI.lastIndexOf(".");
        String scriptFile = requestURI.substring(0, i) + ".groovy";
        while (scriptFile.startsWith("/")) {
            scriptFile = scriptFile.substring(1);
        }
        // 这样子做第一次会非常的慢，这个需要注意的
        // 可以考虑在加载前将所有的文件都扫描，然后放入一个map中，之后从map获取对应的类型
        final Object o = templateEngineProvider.loadScript(scriptFile);
        if (o instanceof Script) {
            webContext.setVariable("script", o);
        } else if (o instanceof IPageScript) {
            Map<String, Object> params = new HashMap<>();
            if (request.getServletContext().getAttribute("storageFactory") != null) {
                IStorageFactory storageFactory = (IStorageFactory) request.getServletContext().getAttribute("storageFactory");
                params.put("storageFactory", storageFactory);
            }
            ((IPageScript) o).handler(webContext, params);
        }
    }
}
